<?php


namespace app\partneradmin\controller;


use app\api\controller\Adjustqueue;
use app\api\controller\Payment;
use app\api\model\AppPayConfig;
use app\partneradmin\model\Partner;
use app\partneradmin\model\SourceMaterialConfig;
use app\api\controller\Pay;
use app\partneradmin\model\Category;
use app\partneradmin\model\CustomerServiceAccount;
use app\partneradmin\model\CustomerServiceAccountMiddle;
use app\partneradmin\model\PayView;
use app\common\controller\partneradmin\Base;
use app\partneradmin\model\PayConfig;
use app\partneradmin\model\User;
use think\Db;
use think\Exception;
use think\exception\PDOException;
use think\exception\ValidateException;
use think\Log;

class Order extends Base
{
    protected $noNeedLogin = [];

    protected $model;


    public function _initialize()
    {
        parent::_initialize();
        $this->model = new \app\partneradmin\model\Order();
    }

    /**
     * 查看
     */
    public function index()
    {
        //设置过滤方法
        if ($this->request->isPost()) {
            $page = $this->request->post('page', 1);
            $size = $this->request->post('page_size', 10);
            $sort = $this->request->post('sort', 'id');
            $order = $this->request->post('order', 'desc');
            $outTradeNo = $this->request->post('out_trade_no', '');
            $userId = $this->request->post('user_id', '');
            $pay_view_id = $this->request->post('pay_view_id', '');
            $pay_config_id = $this->request->post('pay_config_id', '');
            $status = $this->request->post('status', '');
            $customerServicePersonnelId = $this->request->post('customer_service_personnel_id', '');
            $customerServiceGroupId = $this->request->post('customer_service_group_id', '');
            $serviceGroupName = $this->request->post('customer_service_group_name', '');
            $servicePersonnelName = $this->request->post('customer_service_personnel_name', '');
            $real_amount = $this->request->post('real_amount', '');
            $userPhone = $this->request->post('user_phone', '');

            $partner_id = $this->admin['partner_id'];
            $startTime = $this->request->post('start_time', '');
            $endTime = $this->request->post('end_time', '');
            $payStartTime = $this->request->post('pay_start_time', '');
            $payEndTime = $this->request->post('pay_end_time', '');
            if ($startTime != '' && $endTime != '') {
                $startOpenTime = strtotime($startTime . '00:00:00');//格式化开始时间
                $endOpenTime = strtotime($endTime . '23:59:59');//格式化结束时间
                $where['create_time'] = ['between', [$startOpenTime, $endOpenTime]];
            }
            if ($payStartTime != '' && $payEndTime != '') {
                $payStartTime = strtotime($payStartTime . '00:00:00');//格式化开始时间
                $payEndTime = strtotime($payEndTime . '23:59:59');//格式化结束时间
                $where['pay_success_time'] = ['between', [$payStartTime, $payEndTime]];
            }
            $where['partner_id'] = $partner_id;
            $adminCustomerServiceInfo = $this->getCustomerServiceInfo();
            switch ($this->admin['rule']) {
                case 1:
//                    $customerServiceGroupId = $adminCustomerServiceInfo['customer_service_personnel_info']['customer_service_group_id'];
//                    break; TODO 组长可查看组员信息功能关闭
                 case 2:
                    $customerServicePersonnelId = $adminCustomerServiceInfo['customer_service_personnel_info']['id'];
                    break;
            }

            if ($customerServicePersonnelId != '') {
                $where['customer_service_personnel_id'] = $customerServicePersonnelId;
            }
            if ($customerServiceGroupId != '') {
                $where['customer_service_group_id'] = $customerServiceGroupId;
            }
            $data = [
                'total' => 0,
                'list' => [],
                'totalPage' => 0
            ];
            //查找客服组
            if ($serviceGroupName != '') {
                $groupInfo = \app\partneradmin\model\CustomerServiceGroup::get(['name' => trim($serviceGroupName)]);
                if (empty($groupInfo)) {
                    $this->success('列表', '', $data);
                }
                if ($customerServiceGroupId != '') {
                    if ($customerServiceGroupId != $groupInfo['id']) {
                        $this->success('列表', '', $data);
                    }
                }
                $where['customer_service_group_id'] = $groupInfo['id'];
            }
            //查找客服人员
            if ($servicePersonnelName != '') {
                $personnelInfo = \app\partneradmin\model\CustomerServicePersonnel::get(['name' => trim($servicePersonnelName)]);
                if (empty($personnelInfo)) {
                    $this->success('列表', '', $data);
                }
                if ($customerServicePersonnelId != '') {
                    if ($customerServicePersonnelId != $personnelInfo['id']) {
                        $this->success('列表', '', $data);
                    }
                }
                $where['customer_service_personnel_id'] = $personnelInfo['id'];
            }

            //查找用户
            if ($userPhone != '') {
                $userInfo = \app\partneradmin\model\User::get(['username' => trim($userPhone)]);
                if (empty($userInfo)) {
                    $this->success('列表', '', $data);
                }
                $where['user_id'] = $userInfo['id'];
            }
            if ($pay_view_id != '') {
                $where['pay_view_id'] = $pay_view_id;
            }
            if ($userId != '') {
                $where['user_id'] = $userId;
            }
            if ($status != '') {
                $where['status'] = $status;
            }
            if ($pay_config_id != '') {
                $where['pay_config_id'] = $pay_config_id;
            }
            if ($outTradeNo != '') {
                $where['out_trade_no'] = ['like', '%' . trim($outTradeNo) . '%'];
            }
            if ($real_amount != '') {
                $where['real_amount'] = ['like', '%' . trim($real_amount) . '%'];
            }
            $where['is_del'] = 0;
            $fields = [
                'id',
                'out_trade_no',
                'user_id',
                'real_amount',
                'trade_no',
                'source',
                'app_base_id',
                'pay_config_id',
                'pay_view_id',
                'pay_url',
                'status',
                'create_time',
                'pay_success_time',
                'country_config_id',
                'diff_time',
                'shop_url',
                'utr',
            ];
            $list = $this->model
                ->with(['PayConfig', 'PayView'])
                ->field(implode(',', $fields))
                ->where($where)
                ->page($page, $size)
                ->order($sort, $order)
                ->select()
                ->toArray();
            $user = new User();
            $list = $user->formatOrderData($list);
            $payConfigList = PayConfig::select()->toArray();
            $payConfigList = array_column($payConfigList, null, 'id');
            //取出所有国家列表
            $countryConfigList = \app\admin\model\CountryConfig::select()->toArray();
            $countryConfigList = array_column($countryConfigList, null, 'id');
            foreach ($list as $key => $value) {
                $value['pay_config_name'] = empty($payConfigList[$value['pay_config_id']]) ? "" : $payConfigList[$value['pay_config_id']]['title'];
                $value['pay_success_time'] = empty($value['pay_success_time']) ? "" : $value['pay_success_time'];
                $value['country_name'] = empty($countryConfigList[$value['country_config_id']]) ? '' : $countryConfigList[$value['country_config_id']]['name'];
                $value['diff_time'] = date('Y-m-d H:i:s', $value['diff_time']);
                //如果支付通道为oepay  则显示商城url
                if ($value['pay_config_id'] == 43) {
                    $value['pay_url'] = $value['shop_url'];
                }
                $list[$key] = $value;
            }
            $total = $this->model->where($where)->count('id');
            $totalPage = ceil($total / $size);
            $data = [
                'total' => $total,
                'list' => $list,
                'totalPage' => $totalPage
            ];
            $this->success('列表', '', $data);
        }
    }

    /**
     * 补单接口
     */
    public function orderSupplement($ids)
    {
        $this->error('不可操作!');
        $row = $this->model->get($ids);
        if (!$row) {
            $this->error('不存在的数据', '', [], 404);
        }
        if ($this->request->isPost()) {
            $params = $this->request->post("");
            if ($params) {
                $params = $this->preExcludeFields($params);
                $result = false;
                Db::startTrans();
                try {
                    $updateData = [
                        'status' => 3,
                        'pay_success_time' => empty($params['pay_success_time']) ? time() : strtotime($params['pay_success_time'])
                    ];
                    $result = $row->allowField(true)->isUpdate(true)->save($updateData);
                    $updatePayViewData = [
                        'status' => 3
                    ];
                    PayView::update($updatePayViewData, ['id' => $row['pay_view_id']]);
                    $payView = PayView::get($row['pay_view_id']);
                    if (!empty($payView)) {
                        $payment = new Payment();
//                        $payment->adjustReport($row, $payView);
                        $payment->payBusiness($row, $payView);
                        Adjustqueue::dispatch($row['id'], $payView['id']);
                    }
                    Db::commit();
                } catch (ValidateException $e) {
                    Db::rollback();
                    $this->error($e->getMessage());
                } catch (PDOException $e) {
                    Db::rollback();
                    $this->error($e->getMessage());
                } catch (Exception $e) {
                    Db::rollback();
                    $this->error($e->getMessage());
                }
                if ($result !== false) {
                    $this->success('修改成功');
                } else {
                    $this->error('修改失败');
                }
            }
            $this->error('参数不能为空！');
        }
    }

    /**
     * 拉空单详情
     * @param $ids
     */
    public function getOperationEmptyOrderInfo($user_id)
    {

        $userInfo = \app\partneradmin\model\User::get($user_id);
        if (empty($userInfo)) {
            $this->error('不存在的用户数据', '', [], 404);
        }
        $groupList = [
            '1' => '贷款',
            '2' => '还款',
            '3' => '提现',
        ];
        //查看用户之前是否有支付业务
        $payViewRow = \app\partneradmin\model\PayView::where('user_id', $user_id)->order('id', 'desc')->find();
        if (!empty($payViewRow)) {
            $catInfo = \app\partneradmin\model\Category::get(['nickname' => $payViewRow['type']]);
        }
        $payConfigInfo = [];
        if (!empty($payViewRow['pay_config_id'])) {
            $payConfigInfo = PayConfig::get($payViewRow['pay_config_id']);
        } else {
            $appPayConfig = AppPayConfig::where(['app_base_id' => $userInfo['app_base_id']])->where(['country_config_id' => $userInfo['country_config_id']])->find();
            if (empty($appPayConfig)) {
                $appPayConfig = AppPayConfig::where(['app_base_id' => 0])->where(['country_config_id' => $userInfo['country_config_id']])->find();
            }
            $payConfigInfo = PayConfig::get($appPayConfig['other_pay_config_id']);
        }
        $data = [
            'group' => empty($payViewRow) ? '' : $payViewRow['group'],
            'pay_config_id' => empty($payConfigInfo) ? '' : $payConfigInfo['id'],
            'other_information' => empty($payConfigInfo) ? '' : $payConfigInfo['other_information'],
            'group_name' => empty($payViewRow) ? '' : $groupList[$payViewRow['group']],
            'type' => empty($payViewRow) ? '' : $payViewRow['type'],
            'type_name' => empty($catInfo) ? '' : $catInfo['name'],
            'is_abandoned' => empty($payViewRow) ? 0 : $payViewRow['is_abandoned'],
            'generate_type' => empty($payViewRow) ? 2 : $payViewRow['generate_type'],
        ];
        $this->success('拉空单详情', '', $data);
    }

    /**
     * 拉空单
     */
    public function operationEmptyOrder($user_id)
    {
        if($this->admin['rule'] == 3){
            $this->error('非客服不可操作!');
        }
        $userInfo = User::get($user_id);
        if (empty($userInfo)) {
            $this->error('不存在的用户数据', '', [], 404);
        }
        if ($this->request->isPost()) {
            $params = $this->request->post("");
            if (!empty($params)) {
                $result = false;
                Db::startTrans();
                try {
                    if (!is_int((int)$params['num'])) {
                        $this->error('空单数量只能为整数！');
                    }
                    if (empty($params['amount_money'])) {
                        $this->error('订单金额不能为空！');
                    }
                    if (empty($params['pay_config_id'])) {
                        $this->error('支付商户id不能为空！');
                    }
                    if ($params['group'] == '') {
                        $this->error('支付类型不能为空！');
                    }
                    if ($params['type'] == '') {
                        $this->error('支付业务不能为空！');
                    }
                    if ($params['is_quota'] == '') {
                        $this->error('是否添加到贷款额度不能为空！');
                    }
                    $payConfigInfo = \app\partneradmin\model\PayConfig::get($params['pay_config_id']);
                    if (empty($payConfigInfo)) {
                        $this->error('支付通道不能为空！');
                    }
                    $sourceMaterialInfo = SourceMaterialConfig::where(['secondary_classification' => $params['type']])->find();
                    if (empty($sourceMaterialInfo)) {
                        $this->error('素材不存在');
                    }
                    //查找客服id
                    $customer_service_account_middle = \app\partneradmin\model\CustomerServiceAccountMiddle::get($userInfo['customer_service_account_middle_id']);
                    $customer_service_account = \app\partneradmin\model\CustomerServiceAccount::get($customer_service_account_middle['customer_service_account_id']);
                    $catInfo = Category::get(['nickname' => $params['type']]);
                    //生成支付页面
                    //生成订单
                    $setOrder = [];
                    $resData = [];
                    for ($i = 0; $i < $params['num']; $i++) {
                        $setPayView = [
                            'title' => $sourceMaterialInfo['title'],
                            'content' => $sourceMaterialInfo['content'],
                            'group' => $params['group'],
                            'type' => $params['type'],
                            'generate_type' => empty($params['generate_type']) ? 2 : $params['generate_type'],
                            'user_id' => $userInfo['id'],
                            'app_base_id' => $userInfo['app_base_id'],
                            'amount_money' => $params['amount_money'],
                            'is_quota' => empty($params['is_quota']) ? 0 : $params['is_quota'],
                            'source' => $userInfo['source'],
                            'is_abandoned' => 1,
                            'status' => 1,
                            'create_time' => time(),
                            'data_id' => '',
                            'partner_id' => $customer_service_account['partner_id'],
                            'customer_service_group_id' => $customer_service_account['customer_service_group_id'],
                            'customer_service_personnel_id' => $customer_service_account['customer_service_personnel_id'],
                            'diff_time' => timeZoneConvert($userInfo['country_config_id'])
                        ];
                        $payViewId = PayView::insertGetId($setPayView);
                        //模拟下单做支付统一处理
                        $payConfigInfo = PayConfig::get($params['pay_config_id']);
                        $out_trade_no = createTradeNo();
                        $appendStr = 'XX';
                        //获取用户所属小组
                        $userInfo = User::get($setPayView['user_id']);
                        $accountMiddleInfo = CustomerServiceAccountMiddle::get($userInfo['customer_service_account_middle_id']);
                        $accountInfo = CustomerServiceAccount::get($accountMiddleInfo['customer_service_account_id']);
                        if (!empty($accountInfo)) {
                            $groupInfo = \app\partneradmin\model\CustomerServiceGroup::get($accountInfo['customer_service_group_id']);
                            $partner = Partner::get($groupInfo['partner_id']);
                            if (!empty($groupInfo)) {
                                $appendStr = substr($groupInfo['name'], 0, 2);
                                $partnerStr = substr($partner['name'], 0, 2);
                                $appendStr = $partnerStr . $appendStr;
                            }
                        }
                        $out_trade_no = $out_trade_no . $appendStr;
                        $orderNum = 'TD' . Pay::$accessPay[$payConfigInfo['nickname']] . $out_trade_no;
                        $payUrlData = $this->getPayUrl($params['pay_config_id'], $userInfo['id'], $orderNum, $params['amount_money']);
                        $setOrder = [
                            'pay_view_name' => $sourceMaterialInfo['title'],
                            'generate_type' => empty($params['generate_type']) ? 2 : $params['generate_type'],
                            'out_trade_no' => $orderNum,//我们的订单id
                            'user_id' => $userInfo['id'],
                            'real_amount' => $params['amount_money'],
                            'trade_no' => '',
                            'source' => $userInfo['source'],
                            'app_base_id' => $userInfo['app_base_id'],
                            'pay_config_id' => $params['pay_config_id'],
                            'pay_url' => $payUrlData['pay_url'],
                            'pay_view_id' => $payViewId,
                            'send_params_json' => $payUrlData['send_params_json'],
                            'send_back_json' => $payUrlData['send_back_json'],
                            'status' => 1,
                            'create_time' => time(),
                            'partner_id' => $customer_service_account['partner_id'],
                            'customer_service_group_id' => $customer_service_account['customer_service_group_id'],
                            'customer_service_personnel_id' => $customer_service_account['customer_service_personnel_id'],
                            'diff_time' => timeZoneConvert($userInfo['country_config_id'])
                        ];
                        //通道为43时 生成商城支付链接
                        if ($params['pay_config_id'] == 43) {
                            $setOrder['shop_url'] = 'https://shop.civicloftsden.com/buy-now?user_id=' . $userInfo['id'] . '&out_trade_no=' . $orderNum;
                        }
                        $orderId = $this->model->allowField(true)->insertGetId($setOrder);
                        //修改支付页面所属data_id
                        PayView::update(['data_id' => $orderId], ['id' => $payViewId]);
                        $setPayView['type_name'] = $catInfo['name'];
                        //通道为43时 生成商城支付链接
                        if ($params['pay_config_id'] == 43) {
                            //通知商城  生成一条对应的商城内容
                            $setOrder['pay_url'] = $setOrder['shop_url'];
                        }
                        $resData[] = [
                            'order_info' => [
                                'out_trade_no' => $orderNum,
                                'pay_config_name' => $payConfigInfo['title'],
                                'other_information' => empty($payConfigInfo) ? '' : $payConfigInfo['other_information'],
                                'user_mobile' => $userInfo['mobile'],
                                'customer_service_account' => $customer_service_account['username'],
                                'amount_money' => $params['amount_money'],
                                'generate_type' => empty($params['generate_type']) ? 2 : $params['generate_type'],
                                'pay_url' => $setOrder['pay_url'],
                            ],
                            'pay_view_info' => $setPayView
                        ];
                    }
                    $result = true;
                    Db::commit();
                } catch (ValidateException $e) {
                    Db::rollback();
                    $this->error($e->getMessage());
                } catch (PDOException $e) {
                    Db::rollback();
                    $this->error($e->getMessage());
                } catch (Exception $e) {
                    Db::rollback();
                    $this->error($e->getMessage());
                }
                if ($result !== false) {
                    //通道为43时 生成商城支付链接
                    if ($params['pay_config_id'] == 43) {
                        foreach ($resData as $key => $val) {
                            //通知商城  生成一条对应的商城内容
                            $url = 'https://shopad.civicloftsden.com/api/index/orderDetail';
                            request_post($url, ['user_id' => $val['pay_view_info']['user_id'], 'out_trade_no' => $val['order_info']['out_trade_no']]);
                        }
                    }
                    $this->success('操作成功', '', $resData);
                } else {
                    $this->error('操作失败');
                }


            } else {
                $this->error('参数不能为空！');
            }
        }
    }

    //获取支付链接以及一系列参数
    public function getPayUrl($pay_config_id, $user_id, $out_trade_no, $amount_money)
    {
        $userInfo = User::get($user_id);
        $payConfigInfo = PayConfig::get($pay_config_id);
        $payConfigKey = unserialize($payConfigInfo['configjson']);
        $payConfigKey = json_decode($payConfigKey, true);
        $payUrl = new Pay();
        //各种通道需要什么字段持续做增量
        $createPayUrlData = [
            'out_trade_no' => $out_trade_no,
            'amount_money' => $amount_money,
            'user_id' => $userInfo['id'],
            'user_name' => $userInfo['username'],
            'user_email' => '',
            'user_phone' => $userInfo['mobile'],
        ];
        $payConfigKey = array_values($payConfigKey)[0];
        $payUrlRes = $payUrl->getPayUrl($payConfigKey['appId'], $payConfigKey['appKey'], $payConfigInfo['nickname'], $createPayUrlData);
        if (empty($payUrlRes['payurl'])) {
            //记录错误日志
            Log::error(json_encode($payUrlRes));
            $this->error('支付链接生成失败!');
        }
        return [
            'pay_url' => $payUrlRes['payurl'],
            'send_params_json' => json_encode($createPayUrlData),
            'send_back_json' => json_encode($payUrlRes)
        ];
    }

}